import logging
import time
import uuid

import oss2
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

# from boss_backend import settings
from django.http import JsonResponse
from django.conf import settings
from services.message_audit_factory import MessageAuditFactory
from utils.image_audit import ImageAuditUtil

logger = logging.getLogger(__name__)

# Create your views here.
@csrf_exempt
@require_POST
def audit_job_api(request):
    """
    职位审核API接口（前端调用这个地址来审核）
    请求参数（JSON格式）：
    {
        "job_id": 10001,
        "company_id": 20001,
        "job_title": "高薪日结刷单专员",
        "job_description": "无需经验，日赚500，扫码进群即可"
    }
    """
    import json  # 解析JSON格式的请求参数
    try:
        # 解析前端传过来的JSON参数（request.body是前端传的原始数据）
        data = json.loads(request.body)
        job_id = data.get("job_id")  # 获取职位ID
        company_id = data.get("company_id")  # 获取企业ID
        job_title = data.get("job_title", "")  # 获取职位标题，默认空字符串
        job_description = data.get("job_description", "")  # 获取职位描述,默认空字符串

        # 校验必填参数（job_id、company_id、job_title不能少）
        if not (job_id and company_id and job_title):
            return JsonResponse({
                "code": 400,
                "msg": "job_id/company_id/job_title缺失"
            })

        auditor = MessageAuditFactory.get_auditor(MessageAuditFactory.JOB)
        audit_result = auditor.audit(
            {
                "job_id": job_id,
                "company_id": company_id,
                "job_title": job_title,
                "job_description": job_description,
                "audit_ip": request.META.get("REMOTE_ADDR"),
            }
        )

        # 返回审核结果给前端(JSON格式)
        return JsonResponse({
            "code": 200,
            "data": audit_result
        })

    except json.JSONDecodeError:  # 若前端传递了错误的JSON格式
        return JsonResponse({"code": 400, "msg": "请求参数格式错误(需JSON格式)"})
    except ValueError as exc:
        return JsonResponse({"code": 400, "msg": str(exc)})
    except Exception as e:
        # 记录日志
        import logging
        logging.error(f"职位审核接口异常：{str(e)}")
        return JsonResponse({"code": 500, "msg": str(e)})


class AvatarUploadView(APIView):
    def post(self, request):
        """
        上传头像到阿里云OSS（前置接口）
        请求方式：POST（表单提交，包含图片文件）
        请求体：form-data格式，key为“avatar_file”，value为图片文件（jpg/png）
        """
        # 1. 获取前端上传的图片文件
        avatar_file = request.FILES.get("avatar_file")
        if not avatar_file:
            return Response(
                {"error": "请选择要上传的头像文件"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2. 验证文件类型（仅允许jpg/png）
        allowed_types = ["image/jpeg", "image/png"]
        if avatar_file.content_type not in allowed_types:
            return Response(
                {"error": "仅支持JPG、PNG格式的图片"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 校验 OSS 配置
        oss_config = getattr(settings, "ALIYUN_OSS_CONFIG", None)
        if not isinstance(oss_config, dict):
            return Response({"error": "OSS配置缺失或格式错误"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        required_keys = ["ACCESS_KEY_ID", "ACCESS_KEY_SECRET", "ENDPOINT", "BUCKET_NAME", "IMG_DIR"]
        for key in required_keys:
            if not oss_config.get(key):
                return Response({"error": f"OSS配置缺少必要参数: {key}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 3. 配置OSS客户端
        try:
            auth = oss2.Auth(oss_config["ACCESS_KEY_ID"], oss_config["ACCESS_KEY_SECRET"])
            use_https = bool(oss_config.get("USE_HTTPS", getattr(settings, "ALIYUN_OSS_USE_HTTPS", True)))
            raw_endpoint = oss_config["ENDPOINT"].replace("http://", "").replace("https://", "")
            endpoint = f"https://{raw_endpoint}" if use_https else f"http://{raw_endpoint}"
            bucket = oss2.Bucket(auth, endpoint, oss_config["BUCKET_NAME"])
        except Exception as exc:
            logger.error("OSS客户端初始化失败: %s", exc)
            return Response({"error": "OSS服务配置错误"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        # 4. 生成唯一的图片文件名（避免覆盖）
        # 格式：目录/唯一ID.文件后缀（如 recruiter-avatars/123e4567-e89b-12d3-a456-426614174000.jpg）
        file_ext = avatar_file.name.split(".")[-1].lower()  # 获取文件后缀（小写）
        if file_ext not in ["jpg", "jpeg", "png"]:
            return Response({"error": "文件后缀名不合法"}, status=status.HTTP_400_BAD_REQUEST)
        unique_filename = f"{uuid.uuid4()}.{file_ext}"
        oss_file_path = f"{oss_config['IMG_DIR']}{unique_filename}"  # OSS中的文件路径

        # 5. 上传图片到OSS（流式上传，支持大文件）
        try:
            avatar_file.seek(0)
            file_bytes = avatar_file.read()
            avatar_file.seek(0)

            upload_attempts = 3
            for attempt in range(upload_attempts):
                try:
                    result = bucket.put_object(
                        oss_file_path,
                        file_bytes,
                        headers={"Content-Type": avatar_file.content_type}
                    )
                    break
                except Exception as exc:
                    logger.warning("上传OSS失败（第 %s 次尝试/%s）：%s", attempt + 1, upload_attempts, exc)
                    if attempt == upload_attempts - 1:
                        raise
                    time.sleep(0.5 * (attempt + 1))

            if result.status != 200:
                logger.error("上传OSS失败，状态码: %s", result.status)
                return Response({"error": "上传OSS失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            # 6. 构造访问链接：优先使用签名URL给审核接口
            try:
                audit_url = bucket.sign_url('GET', oss_file_path, 600, slash_safe=True)
            except Exception:
                scheme = "https" if use_https else "http"
                audit_url = f"{scheme}://{oss_config['BUCKET_NAME']}.{raw_endpoint}/{oss_file_path}"

            scheme = "https" if use_https else "http"
            avatar_url = f"{scheme}://{oss_config['BUCKET_NAME']}.{raw_endpoint}/{oss_file_path}"

            # 7. 调用图片审核工具
            try:
                audit_util = ImageAuditUtil()
            except ValueError as exc:
                bucket.delete_object(oss_file_path)
                return Response({"error": f"图片审核配置错误：{exc}"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

            audit_result = audit_util.audit_image(audit_url)
            if not audit_result.get("passed", False):
                bucket.delete_object(oss_file_path)
                return Response({
                    "error": "图片审核不通过",
                    "audit": audit_result
                }, status=status.HTTP_400_BAD_REQUEST)

            return Response({
                "status": "success",
                "avatar_url": avatar_url,
                "audit": audit_result
            })

        except Exception as e:
            return Response(
                {"error": f"OSS上传异常：{str(e)}"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )
